package com.itlong.cloud.controller.scene;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateSceneGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateSceneSaveDTO;
import com.itlong.cloud.POJO.PO.OperateScenePO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateSceneVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateSceneServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.string.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <desc>
 * 场景管理
 * </desc>
 *
 * @createDate 2021-03-25
 */
@RestController
@RequestMapping("/scene")
public class SceneController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(SceneController.class);

    @Autowired
    IOperateSceneServiceClient iOperateSceneServiceClient;

    /**
     * <desc>
     * 添加场景
     * <desc/>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-03-25
     */
    @LoggerInfo(operateDesc = LogDescConstant.SCENE_SAVE_LOG_DESC)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object saveScene(HttpServletRequest request) {
        try {
            OperateSceneSaveDTO saveDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateSceneSaveDTO.class, request);
            if (saveDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (saveDTO.getName() == null || saveDTO.getName().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (saveDTO.getName().length() > 20) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_LENGTH_ERROR.getErrorCode());
            }
            if (iOperateSceneServiceClient.getCountByName(saveDTO.getName()) > 0) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_EXIST.getErrorCode());
            }
            if (saveDTO.getPackageId() == null || saveDTO.getPackageId().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_PACKAGE_KEY_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (saveDTO.getUserType() == null || saveDTO.getUserType().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (StringUtil.isRepeat(saveDTO.getUserType())) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_PARAMS_IS_REPEAT.getErrorCode());
            }
            String[] list = saveDTO.getUserType().split(",");
            for (String item : list) {
                if (item.length() > 20) {
                    return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_LENGTH_ERROR.getErrorCode());
                }
            }
            saveDTO.setSceneId(LogicIdUtil.bussinessId());
            Object loginUser = request.getAttribute("myUserName");
            if (loginUser == null) {
                saveDTO.setCreateUserId("");
                saveDTO.setOperateUserId("");
            } else {
                saveDTO.setCreateUserId(loginUser.toString());
                saveDTO.setOperateUserId(loginUser.toString());
            }
            int res = iOperateSceneServiceClient.saveScene(saveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        } catch (Exception e) {
            throw new DataAccessException("【运营_场景管理_添加场景add】添加场景失败", e);
        }
    }

    /**
     * <desc>
     * 修改场景
     * <desc/>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-03-25
     */
    @LoggerInfo(operateDesc = LogDescConstant.SCENE_UPDATE_LOG_DESC)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateScene(HttpServletRequest request) {
        try {
            OperateSceneSaveDTO saveDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateSceneSaveDTO.class, request);
            if (saveDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (saveDTO.getSceneId() == null || saveDTO.getSceneId().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_ID_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (iOperateSceneServiceClient.getOneBySceneId(saveDTO.getSceneId()) == null) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NOT_EXIST.getErrorCode());
            }
            if (saveDTO.getName() == null || saveDTO.getName().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (saveDTO.getName().length() > 20) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_LENGTH_ERROR.getErrorCode());
            }
            if (iOperateSceneServiceClient.getExcludeCountByName(saveDTO.getName(), saveDTO.getSceneId()) > 0) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_NAME_EXIST.getErrorCode());
            }
            if (saveDTO.getPackageId() == null || saveDTO.getPackageId().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_PACKAGE_KEY_PARAMS_IS_EMPTY.getErrorCode());
            }
            if (saveDTO.getUserType() == null || saveDTO.getUserType().equals("")) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_PARAMS_IS_EMPTY.getErrorCode());
            }
            //编辑时传递[{"userTypeId":"","name":""}]
            JSONArray array = JSONObject.parseArray(saveDTO.getUserType());
            if (array == null) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_ERROR.getErrorCode());
            }
            List<String> userTypeList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                userTypeList.add(array.getJSONObject(i).getString("name"));
            }
            String userTypeText = StringUtils.join(userTypeList, ",");
            if (StringUtil.isRepeat(userTypeText)) {
                return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_PARAMS_IS_REPEAT.getErrorCode());
            }
            String[] list = userTypeText.split(",");
            for (String item : list) {
                if (item.length() > 20) {
                    return new MessageVO(OperateErrorCodeEnum.SCENE_USER_TYPE_LENGTH_ERROR.getErrorCode());
                }
            }
            Object loginUser = request.getAttribute("myUserName");
            if (loginUser == null) {
                saveDTO.setCreateUserId("");
                saveDTO.setOperateUserId("");
            } else {
                saveDTO.setCreateUserId(loginUser.toString());
                saveDTO.setOperateUserId(loginUser.toString());
            }
            int res = iOperateSceneServiceClient.updateScene(saveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        } catch (Exception e) {
            throw new DataAccessException("【运营_场景管理_修改场景update】修改场景失败", e);
        }
    }

    /**
     * <desc>
     * 分页获取场景信息
     * <desc/>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-03-25
     */
    @RequestMapping(value = "/getPage", method = RequestMethod.POST)
    @ResponseBody
    public Object getPage(HttpServletRequest request) {
        try {
            OperateSceneGetPageDTO pageDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateSceneGetPageDTO.class, request);
            if (pageDTO.getCurrentPage() == null || pageDTO.getCurrentPage().equals("")) {
                pageDTO.setCurrentPage("1");
            }
            if (pageDTO.getPageSize() == null || pageDTO.getPageSize().equals("")) {
                pageDTO.setPageSize("15");
            }
            if (pageDTO.getOrderColumn() != null && !pageDTO.getOrderColumn().equals("")) {
                if (pageDTO.getOrderColumn().equals("createTime")) {
                    pageDTO.setOrderColumn("operate_scene.create_time");
                }
            } else {
                pageDTO.setOrderColumn("operate_scene.create_time");
                pageDTO.setOrderRule("DESC");
            }
            Page<OperateSceneVO> page = iOperateSceneServiceClient.getPage(pageDTO);
            MessageVO messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
            return messageVO;
        } catch (Exception e) {
            throw new DataAccessException("【运营_场景管理_场景列表getPage】获取分页列表失败", e);
        }
    }

    @RequestMapping(value = "/userTypeIdCanDelete", method = RequestMethod.POST)
    @ResponseBody
    public Object userTypeIdCanDelete(HttpServletRequest request) {
        try {
            Object userTypeIdObject = request.getAttribute("userTypeId");
            if (userTypeIdObject == null || userTypeIdObject.toString().equals("")) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String userTypeId = userTypeIdObject.toString();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iOperateSceneServiceClient.userTypeIdCanDelete(userTypeId));
        } catch (Exception e) {
            throw new DataAccessException("【运营_场景管理_检查删除userTypeIdCanDelete】检查删除失败", e);
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(HttpServletRequest request) {
        try {
            Object sceneIdObject = request.getAttribute("sceneId");
            if (sceneIdObject == null || sceneIdObject.toString().equals("")) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String sceneId = sceneIdObject.toString();
            OperateScenePO m = iOperateSceneServiceClient.getOneBySceneId(sceneId);
            if (m == null) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode(), "记录不存在");
            }
            Object loginUser = request.getAttribute("myUserName");
            if (loginUser != null) {
                m.setOperateUserId(loginUser.toString());
            }
            int result = iOperateSceneServiceClient.delete(m);
            if (result == 0) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            } else if (result == 1) {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "该记录已被关联使用");
            } else {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "删除失败");
            }
        } catch (Exception e) {
            throw new DataAccessException("【运营_场景管理_删除delete】删除失败", e);
        }
    }

}